// fuel.js
const app = getApp()
const { API } = require('../../utils/api.js')

Page({
  data: {
    userInfo: null,
    fuelTypes: [], // 从后端API获取真实数据，不使用硬编码
    selectedFuel: '',
    selectedFuelName: '',
    selectedFuelPrice: '',
    selectedMethod: '',
    selectedAmount: '',
    customValue: '',
    finalValue: '',
    calculatedVolume: '',
    calculatedAmount: '',
    amountOptions: [50, 100, 200, 300, 500, 1000],
    volumeOptions: [10, 20, 30, 40, 50, 60]
  },

  onLoad() {
    this.loadFuelPrices()
  },

  onShow() {
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },

  async loadFuelPrices() {
    try {
      console.log('开始获取油品类型数据...')
      // 从后端获取油品类型和价格
      const fuelTypes = await API.getFuelTypes()
      console.log('获取到的油品数据:', fuelTypes)

      if (fuelTypes && fuelTypes.length > 0) {
        // 确保价格是字符串格式，便于前端显示
        const formattedFuelTypes = fuelTypes.map(fuel => ({
          ...fuel,
          price: fuel.price.toString()
        }))

        this.setData({
          fuelTypes: formattedFuelTypes
        })
        // 缓存到本地
        wx.setStorageSync('fuelPrices', formattedFuelTypes)
        console.log('油品数据设置成功:', formattedFuelTypes)
      }
    } catch (error) {
      console.error('获取油品价格失败:', error)

      // 如果API调用失败，尝试从本地缓存获取
      const storedPrices = wx.getStorageSync('fuelPrices')
      if (storedPrices && storedPrices.length > 0) {
        console.log('使用缓存的油品数据:', storedPrices)
        this.setData({
          fuelTypes: storedPrices
        })
      } else {
        // 如果缓存也没有，使用默认数据（基于数据库真实数据）
        const defaultFuelTypes = [
          { type: '92', name: '92号汽油', price: '7.23' },
          { type: '95', name: '95号汽油', price: '7.78' },
          { type: '98', name: '98号汽油', price: '8.65' },
          { type: '0', name: '0号柴油', price: '7.10' }
        ]
        console.log('使用默认油品数据:', defaultFuelTypes)
        this.setData({
          fuelTypes: defaultFuelTypes
        })
      }
    }
  },

  selectFuel(e) {
    const type = e.currentTarget.dataset.type
    const currentFuel = this.data.fuelTypes.find(item => item.type === type)
    this.setData({
      selectedFuel: type,
      selectedFuelName: currentFuel ? currentFuel.name : '',
      selectedFuelPrice: currentFuel ? currentFuel.price : ''
    })
    this.calculateResult()
  },

  selectMethod(e) {
    const method = e.currentTarget.dataset.method
    this.setData({
      selectedMethod: method,
      selectedAmount: '',
      customValue: '',
      finalValue: '',
      calculatedVolume: '',
      calculatedAmount: ''
    })
  },

  selectAmount(e) {
    const amount = e.currentTarget.dataset.amount
    this.setData({
      selectedAmount: amount,
      customValue: '',
      finalValue: amount
    })
    this.calculateResult()
  },

  onCustomInput(e) {
    const value = e.detail.value
    this.setData({
      customValue: value,
      selectedAmount: '',
      finalValue: value
    })
    this.calculateResult()
  },

  calculateResult() {
    const { selectedFuel, selectedMethod, finalValue, fuelTypes } = this.data

    if (!selectedFuel || !selectedMethod || !finalValue) {
      return
    }

    const currentFuel = fuelTypes.find(item => item.type === selectedFuel)
    if (!currentFuel) return

    const price = parseFloat(currentFuel.price)
    const input = parseFloat(finalValue)

    if (selectedMethod === 'amount') {
      // 按金额计算升数
      const volume = (input / price).toFixed(2)
      this.setData({
        calculatedVolume: volume
      })
    } else {
      // 按升数计算金额
      const amount = (input * price).toFixed(2)
      this.setData({
        calculatedAmount: amount
      })
    }
  },

  getCurrentFuelName() {
    const { selectedFuel, fuelTypes } = this.data
    const fuel = fuelTypes.find(item => item.type === selectedFuel)
    return fuel ? fuel.name : ''
  },

  getCurrentFuelPrice() {
    const { selectedFuel, fuelTypes } = this.data
    const fuel = fuelTypes.find(item => item.type === selectedFuel)
    return fuel ? fuel.price : ''
  },

  confirmFuel() {
    const { selectedFuel, selectedMethod, finalValue, calculatedVolume, calculatedAmount, userInfo, selectedFuelPrice } = this.data

    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'error'
      })
      return
    }

    const fuelName = this.data.selectedFuelName
    const volume = selectedMethod === 'amount' ? calculatedVolume : finalValue
    const amount = selectedMethod === 'amount' ? finalValue : calculatedAmount

    wx.showModal({
      title: '确认支付',
      content: `确认支付¥${amount}元，预计加注${fuelName} ${volume}升？\n支付成功后将自动创建订单`,
      success: (res) => {
        if (res.confirm) {
          // 直接发起支付，不先创建订单
          this.initiateWechatPayment(volume, amount, fuelName)
        }
      }
    })
  },

  async createFuelOrderAfterPayment(volume, amount, fuelName, paymentId) {
    wx.showLoading({
      title: '正在创建订单...'
    })

    try {
      // 支付成功后创建订单
      const orderData = {
        fuelType: fuelName,
        fuelPrice: parseFloat(this.data.selectedFuelPrice),
        volume: parseFloat(volume),
        prepaidAmount: parseFloat(amount),
        status: 'paid' // 标记为已支付状态
      }

      const order = await API.createOrder(orderData)

      wx.hideLoading()

      wx.showModal({
        title: '支付成功',
        content: `订单号：${order.orderNo}\n支付成功！请前往加油站等待工作人员为您加油`,
        showCancel: false,
        success: () => {
          // 重置表单
          this.resetForm()
          
          // 跳转到订单页面
          wx.switchTab({
            url: '/pages/orders/orders'
          })
        }
      })

      return order

    } catch (error) {
      wx.hideLoading()
      console.error('创建订单失败:', error)
      wx.showToast({
        title: '创建订单失败，请联系客服',
        icon: 'error'
      })
      throw error
    }
  },

  async initiateWechatPayment(volume, amount, fuelName) {
    try {
      wx.showLoading({
        title: '正在发起支付...'
      })

      // 创建临时支付订单（不创建正式订单）
      const paymentData = {
        description: `${fuelName}加油费用`,
        amount: Math.round(parseFloat(amount) * 100), // 转换为分
        fuelType: fuelName,
        volume: parseFloat(volume),
        fuelPrice: parseFloat(this.data.selectedFuelPrice)
      }

      const paymentParams = await API.createPaymentOrder(paymentData)

      wx.hideLoading()

      // 调用微信支付
      wx.requestPayment({
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType,
        paySign: paymentParams.paySign,
        success: (res) => {
          console.log('支付成功:', res)
          // 支付成功后创建订单
          this.handlePaymentSuccess(volume, amount, fuelName, paymentParams.paymentId)
        },
        fail: (err) => {
          console.error('支付失败:', err)
          this.handlePaymentFail(err)
        }
      })

    } catch (error) {
      wx.hideLoading()
      console.error('发起支付失败:', error)
      wx.showToast({
        title: '发起支付失败',
        icon: 'error'
      })
    }
  },

  async handlePaymentSuccess(volume, amount, fuelName, paymentId) {
    wx.showToast({
      title: '支付成功',
      icon: 'success'
    })

    try {
      // 支付成功后创建订单
      await this.createFuelOrderAfterPayment(volume, amount, fuelName, paymentId)
    } catch (error) {
      console.error('支付成功但创建订单失败:', error)
      wx.showModal({
        title: '支付成功',
        content: '支付已成功，但订单创建遇到问题。请联系客服处理，我们会为您补录订单。',
        showCancel: false
      })
    }
  },

  handlePaymentFail(error) {
    if (error.errMsg === 'requestPayment:fail cancel') {
      // 用户取消支付
      wx.showToast({
        title: '支付已取消',
        icon: 'none'
      })
    } else {
      // 其他支付错误
      wx.showToast({
        title: '支付失败，请重试',
        icon: 'error'
      })
    }
    
    // 支付失败不创建订单，用户可以重新尝试
    console.log('支付失败，未创建订单')
  },

  resetForm() {
    this.setData({
      selectedFuel: '',
      selectedFuelName: '',
      selectedFuelPrice: '',
      selectedMethod: '',
      selectedAmount: '',
      customValue: '',
      finalValue: '',
      calculatedVolume: '',
      calculatedAmount: ''
    })
  },

  generateOrderNo() {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')

    return `${year}${month}${day}${hours}${minutes}${seconds}${random}`
  },

  saveFuelOrder(order) {
    // 获取现有订单
    let orders = wx.getStorageSync('fuelOrders') || []
    orders.unshift(order)

    // 只保留最近200条订单
    if (orders.length > 200) {
      orders = orders.slice(0, 200)
    }

    wx.setStorageSync('fuelOrders', orders)
  },

  saveFuelRecord(volume, amount, fuelName) {
    const record = {
      id: Date.now(),
      userId: this.data.userInfo.id,
      userName: this.data.userInfo.name,
      fuelType: fuelName,
      volume: parseFloat(volume),
      amount: parseFloat(amount),
      date: new Date().toISOString(),
      timestamp: Date.now()
    }

    // 获取现有记录
    let records = wx.getStorageSync('fuelRecords') || []
    records.unshift(record)

    // 只保留最近100条记录
    if (records.length > 100) {
      records = records.slice(0, 100)
    }

    wx.setStorageSync('fuelRecords', records)
  },

  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
})